package com.xxyy.mylive.wxapi;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xxyy.mylive.MyApplication;
import com.xxyy.mylive.R;
import com.xxyy.mylive.bean.WxUserInfo;
import com.xxyy.mylive.http.HttpApi;
import com.xxyy.mylive.http.OkHttpUtils;
import com.xxyy.mylive.tools.UiTool;
import com.xxyy.mylive.ui.BaseActivity;
import com.xxyy.mylive.ui.activity.HomeActivity;
import com.xxyy.mylive.ui.activity.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
    private ProgressDialog dialog;

    private IWXAPI api;
    private String APP_ID, APP_SECRET;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_wxentry);
        //使用微信api都必须先使用appid注册
        APP_ID = getResources().getString(R.string.weixin_app_id);
        APP_SECRET = getResources().getString(R.string.weixin_app_secret);
        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void initUI() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        int result = 0;
        //微信登录返回的结果
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                dialog = new ProgressDialog(WXEntryActivity.this);
                dialog.setTitle("登录中");
                dialog.show();
                //授权登录，开始请求用户信息，然后进入首页
                String code = ((SendAuth.Resp) baseResp).code;
//                UiTool.showToast(WXEntryActivity.this, code);
                //暂时先请求普通的token，有效期为2小时
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=" + APP_ID + "&" + "secret=" + APP_SECRET + "&" +
                        "code=" + code + "&grant_type=authorization_code";
                //发起请求
                OkHttpUtils.httpGet(url, myHandler, 1);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //取消登录
                UiTool.showToast(WXEntryActivity.this, "取消登录");
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //授权拒绝
                UiTool.showToast(WXEntryActivity.this, "授权拒绝");
                finish();
                break;
            default:
                //未知。。。。
                UiTool.showToast(WXEntryActivity.this, "未知操作");
                break;
        }
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String result = null;
            switch (msg.what) {
                case 0:
                    //请求失败，返回登录页面
                    result = msg.obj.toString();
                    UiTool.showToast(WXEntryActivity.this, result);
                    finish();
                    break;
                case 1:
                    //获取accessToekn
                    result = msg.obj.toString();
//                    UiTool.showToast(WXEntryActivity.this, result);
                    String accessToken = null;
                    String expired = null;
                    String scope = null;
                    String openId = null;
                    try {
                        JSONObject object = new JSONObject(result);
                        String errCode = object.optString("errcode", null);
                        if (null == errCode) {
                            //获取token成功

                            accessToken = object.getString("access_token");
                            expired = object.getString("expires_in");
                            openId = object.getString("openid");
                            scope = object.getString("scope");
                            // TODO: 2016/10/27 此处应该保存token.下次启动app时检查，如果没过期自动登录
                            // 检查token：https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
//                            UiTool.showToast(WXEntryActivity.this, "微信请求信息=" + accessToken + "...." + expired + "..." + scope);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        finish();
                    }

                    //获取用户信息
                    String url = HttpApi.WEIXIN_BASE_URL + "/sns/userinfo?" + "access_token=" + accessToken
                            + "&openid=" + openId;
//                    UiTool.showToast(WXEntryActivity.this, "toekn=" + accessToken + "...openid=" + openId);
                    OkHttpUtils.httpGet(url, this, 2);
                    break;
                case 2:
                    //获取用户信息成功，进入首页
                    result = msg.obj.toString();
                    Gson gson = new Gson();
                    WxUserInfo userInfo = gson.fromJson(result, WxUserInfo.class);
                    //保存用户信息
                    MyApplication application = (MyApplication) getApplicationContext();
                    application.saveUserInfo(userInfo);

                    dialog.dismiss();
                    //进入首页
                    startActivity(new Intent(WXEntryActivity.this, HomeActivity.class));
                    //关闭授权页和登录页面
                    LoginActivity.instance.finish();
                    finish();
                    break;
            }
        }
    };
}
